import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { addPunch, updatePunch } from "@/api/flandre-ui/request";
import { message } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { thStaffsGetStaffsList } from "@/api/system/user";
let staffId: String;
const PunchDrawer = (props: { register: Fn; reload: Fn }) => {
	const { t } = useTranslation();
	const en_vi = "HRMS.punchManagement";
	const [action, setAction] = useState(""); // 用来区分新增还是修改
	const [currentPkId, setCurrentPkId] = useState("");

	const punchFormSchema: FormSchema[] = [
		{
			label: t(`HRMS.leaveApproval.staffName`),
			field: "staffName", //姓名
			component: "ApiSelect",
			componentProps: {
				api: thStaffsGetStaffsList,
				labelField: "staffName",
				valueField: "staffName",
				onChange: (_: any, value: any) => {
					if (!value) return;
					staffId = value.staffId;
				},
				onBlur: async () => {
					// 获取真实时间和地址
					try {
						const currentTime = new Date().toISOString().slice(0, 19).replace("T", " ");

						// 获取地理位置信息
						const getGeolocation = () =>
							new Promise((resolve, reject) => {
								if (!navigator.geolocation) {
									reject(t(`${en_vi}.geolocation`));
									return;
								}
								navigator.geolocation.getCurrentPosition(
									position => {
										const { latitude, longitude } = position.coords;
										resolve({ latitude, longitude });
									},
									error => {
										reject(`${t(`${en_vi}.geolocation`)}: ${error.message}`);
									}
								);
							});

						const { latitude, longitude }: any = await getGeolocation();

						// 获取详细地址信息
						const response = await fetch(
							`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`
						);
						const data = await response.json();

						// 提取地址信息
						const { address } = data;
						const addressInfo = {
							addrInfo: data.display_name || t(`${en_vi}.clockInTime`),
							countryCode: address.country_code?.toUpperCase() || t(`${en_vi}.unknown`),
							provinceCode: address.state || t(`${en_vi}.unknown`),
							cityCode: address.city || address.town || address.state_district || t(`${en_vi}.unknown`),
							districtCode: address.suburb || address.city_district || t(`${en_vi}.unknown`),
							addrDetail: address.road || t(`${en_vi}.unknown`)
						};

						// 自动填充表单数据
						setFieldsValue({
							lockinDtime: currentTime,
							addrLongitude: longitude,
							addrLatitude: latitude,
							...addressInfo
						});
						message.success(t(`${en_vi}.fields`));
					} catch (error: any) {
						message.error(error.toString());
					}
				}
			}
		},
		{
			label: t(`${en_vi}.clockInTime`),
			field: "lockinDtime",
			component: "Input",
			colProps: { span: 24 },
			componentProps: {
				disabled: false // 自动填充后不可编辑
			}
		},
		{
			label: t(`${en_vi}.clockInArea`),
			field: "lockinAreaId",
			component: "Input",
			colProps: { span: 24 },
			componentProps: { disabled: false }
		},
		{
			label: t(`${en_vi}.addressInfo`),
			field: "addrInfo",
			component: "Input",
			colProps: { span: 24 },
			componentProps: { disabled: false }
		},
		{
			label: t(`${en_vi}.longitude`),
			field: "addrLongitude",
			component: "InputNumber",
			colProps: { span: 24 },
			componentProps: { disabled: false }
		},
		{
			label: t(`${en_vi}.latitude`),
			field: "addrLatitude",
			component: "InputNumber",
			colProps: { span: 24 },
			componentProps: { disabled: false }
		},
		{
			label: t(`${en_vi}.countryCode`),
			field: "countryCode",
			component: "Input",
			colProps: { span: 24 },
			componentProps: { disabled: false }
		},
		{
			label: t(`${en_vi}.provinceCode`),
			field: "provinceCode",
			component: "Input",
			colProps: { span: 24 },
			componentProps: { disabled: false }
		},
		{
			label: t(`${en_vi}.cityCode`),
			field: "cityCode",
			component: "Input",
			colProps: { span: 24 },
			componentProps: { disabled: false }
		},
		{
			label: t(`${en_vi}.districtCode`),
			field: "districtCode",
			component: "Input",
			colProps: { span: 24 },
			componentProps: { disabled: false }
		},
		{
			label: t(`${en_vi}.detailedAddress`),
			field: "addrDetail",
			component: "Input",
			colProps: { span: 24 },
			componentProps: { disabled: false }
		},
		{
			label: t(`${en_vi}.status`),
			field: "status",
			component: "Select",
			colProps: { span: 24 },
			componentProps: {
				options: [
					{ label: t(`${en_vi}.regular`), value: "0" },
					{ label: t(`${en_vi}.probative`), value: "1" },
					{ label: t(`${en_vi}.resigned`), value: "2" }
				]
			}
		}
	];

	const [registerForm, { validateFields, resetFields, setFieldsValue }] = useForm({
		labelWidth: 120,
		schemas: punchFormSchema,
		showActionButtonGroup: false
	});

	const [registerDrawer, { closeDrawer }] = useDrawerInner(props.register, data => {
		resetFields();
		const record = data.record || {};
		setAction(data.action || "add");
		if (data.action === "edit") {
			setCurrentPkId(record.pkId);
			setFieldsValue(record);
		}
	});

	async function handleSubmit() {
		try {
			let values = await validateFields();
			values = {
				...values,
				staffId: staffId
			};
			if (action === "edit") {
				values.pkId = currentPkId;
				await updatePunch(values);
				message.success(t("kevin_ui.updateSuccess"));
			} else {
				await addPunch(values);
				message.success(t("kevin_ui.addedSuccessfully"));
			}
			props.reload();
			closeDrawer();
		} catch (error) {
			message.error(t("kevin_ui.operationFailed"));
		}
	}

	return (
		<BasicDrawer
			{...props}
			title={action === "edit" ? t(`${en_vi}.editPunch`) : t(`${en_vi}.addPunch`)}
			register={registerDrawer}
			ok={handleSubmit}
		>
			<BasicForm register={registerForm} />
		</BasicDrawer>
	);
};

export default PunchDrawer;
